#include "GameFont.h"
#include "Exception.h"

using namespace std;

HDC CGameFont::m_hDeviceContext = NULL;

CGameFont::CGameFont() : m_uiListBase(0)
{
}

CGameFont::~CGameFont()
{
	if (m_uiListBase)
		glDeleteLists(m_uiListBase,255);
	DeleteObject(m_hFont);
}

void CGameFont::CreateFont(const std::string& strTypeface, 
						   int iFontHeight,
						   int iFontWeight)
{
	if (!m_hDeviceContext)
	{
		string strError = "Impossible to create the font: ";
		strError += strTypeface;
		throw CException(strError);
		return;
	}

	m_uiListBase = glGenLists(255);
	if (m_uiListBase == 0)
	{
		string strError = "Impossible to create the font: ";
		strError += strTypeface;
		throw CException(strError);
		return;
	}

	m_hFont = ::CreateFont(-iFontHeight,
								  0,
								  0,
								  0,
								  iFontWeight,
								  FALSE,
								  FALSE,
								  FALSE,
								  ANSI_CHARSET,
								  OUT_TT_PRECIS,
								  CLIP_DEFAULT_PRECIS,
								  ANTIALIASED_QUALITY,
								  FF_DONTCARE|DEFAULT_PITCH,
								  strTypeface.c_str());
	if (m_hFont == NULL)
	{
		m_uiListBase = 0;
		string strError = "Impossible to create the font: ";
		strError += strTypeface;
		throw CException(strError);
		return;
	}

	HFONT hOldFont = (HFONT)SelectObject(m_hDeviceContext, m_hFont);
	wglUseFontBitmaps(m_hDeviceContext, 0, 255, m_uiListBase);	
	SelectObject(m_hDeviceContext, hOldFont);	
}

TRectanglei CGameFont::GetTextSize(const std::string& strText)
{
	SIZE TextSize;
	HFONT hOldFont = (HFONT)SelectObject(m_hDeviceContext, m_hFont);
	GetTextExtentPoint32(m_hDeviceContext,strText.c_str(),(int)strText.size(),&TextSize);
	SelectObject(m_hDeviceContext, hOldFont);	

	TRectanglei newTextSize(0,TextSize.cy,0,TextSize.cx);
	return newTextSize;
}

void CGameFont::DrawText(const std::string& strText, 
						 int XPos, int YPos,
						 GLfloat fRed, 
						 GLfloat fGreen, 
						 GLfloat fBlue)
{
	if (m_uiListBase == 0)
	{
		throw CException("Impossible to diplay the text.");
		return;
	}

	glDisable(GL_TEXTURE_2D);

	glColor3f(fRed, fGreen, fBlue);
	glRasterPos2i(XPos, YPos);

	glPushAttrib (GL_LIST_BIT);

		glListBase(m_uiListBase);
	
		glCallLists((GLsizei)strText.size(), GL_UNSIGNED_BYTE, 
					(GLubyte *)strText.c_str());
    glPopAttrib ();

	glColor3f(1.0, 1.0, 1.0);

	glEnable(GL_TEXTURE_2D);
}
